梦入琼楼寒有月,行过石树冻无烟

CSS nth-child and calc as well as position:hover


nth-child 根据 MDN 的概述中的作用为找到所有当前元素的兄弟元素,然后按照先后顺序从1开始进行排序,而calc的作用则是允许在声明 CSS属性中执行计算

那么通过使用 nth-child 和 calc 以及 position 和 :hover也许会实现出一种根据鼠标移动而移动的效果,具体可以使用多个元素进行定义,如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noto+Sans+SC:100,300,400,500,700,900">
</head>
<body>
<div class="cell"></div>
<!-- 99 -->
<div class="con">
<div class="squ"></div>
</div>
</body>
</html>

那么 SCSS 样式可以为他设置一个基础的背景颜色和网格让其显得更好理解,那么首先我们将con的X,Y位置设置为0:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
*, *::before, *::after {
padding: 0;
margin: 0 auto;
box-sizing: border-box;
}
body {
background-color: black;
height: 100vh;
// 设置网格
display: grid;
grid-template: repeat(10, 1fr) / repeat(10, 1fr);
}
.cell {
width: 100%;
height: 100%;
border: 1px solid white;
z-index: 2;
}
.con {
--positionX: 0;
--positionY: 0;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
}
.squ {
width: calc(100px + var(--positionX) * 20px);
height: calc(100px + var(--positionY) * 20px);
background: white;
transition: all 0.3s;
}

之后通过将 cell使用nth-child:hover来进行绑定con的位置数据:

1
2
3
4
5
6
7
8
@for $i from 0 to 10 {
.cell:nth-child(10n + #{$i + 1}):hover ~ .con {
--positionX: #{$i};
}
.cell:nth-child(n + #{10 * $i + 1}):nth-child(-n + #{10 * ($i + 1)}):hover ~ .con {
--positionY: #{$i};
}
}

CSS(通过 CSS 则更加直观)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.cell:nth-child(10n + 1):hover ~ .con {
--positionX: 0; }

.cell:nth-child(n + 1):nth-child(-n + 10):hover ~ .con {
--positionY: 0; }

.cell:nth-child(10n + 2):hover ~ .con {
--positionX: 1; }

.cell:nth-child(n + 11):nth-child(-n + 20):hover ~ .con {
--positionY: 1; }

.cell:nth-child(10n + 3):hover ~ .con {
--positionX: 2; }

.cell:nth-child(n + 21):nth-child(-n + 30):hover ~ .con {
--positionY: 2; }

.cell:nth-child(10n + 4):hover ~ .con {
--positionX: 3; }

当鼠标移动到到 cell 1或21……的时候,则会改变.con相应位置信息来达到使样式移动的效果(配合上过渡)。

⬅️ Go back